import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index.js'
import router from '@/router/index.js'

const request = axios.create({
  // baseURL: 'http://ihrm-java.itheima.net/api'
  baseURL: '/api'
})
request.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.state.user.token) {
    config.headers.Authorization = 'Bearer ' + store.state.user.token
  }
  return config
}, error => {
  // Do something with request error
  return Promise.reject(error)
})

request.interceptors.response.use(response => {
  // 成功处理
  // Do something before response is sent
  const { data: { success, data, message }} = response
  if (success) {
    // 返回res.data.data => token
    return data
  } else {
    Message.error(message)
    throw new Error(message)
  }
  // return response
}, error => {
  // 错误出路
  // Do something with response error

  // 处理token过期问题   状态码为401时，表示token过期
  if (error.response && error.response.status === 401) {
    // 退出
    store.dispatch('user/logout')
    // 返回登录页面
    return router.push('/login')
  }
  Message.error('服务器错误，请稍后重试')
  return Promise.reject(error)
})

export default request
